#include "sendfileclass.h"
#include <QDebug>
static const int blocksize=5000;
static const QString address="127.0.0.1";
static const quint64 port=8889;
SendFileClass::SendFileClass(QObject *parent) : QObject(parent){
    sendfilesocket=nullptr;
    sendingfile=nullptr;
    senddonesize=0;
    totalsize=0;
    index=1;
}

void SendFileClass::initSendFileClass()
{
    sendfilesocket=new QTcpSocket;
    sendfilesocket->connectToHost(address,port);
    connect(sendfilesocket,&QTcpSocket::readyRead,this,&SendFileClass::Verify);
}

//获取任务，与队列类的有任务的信号绑定
void SendFileClass::getTask()
{
    QPair<QPair<QString,QString>,QString> task=SendQueue::getInstance()->getTask();
    sendFile(task.first.first,task.first.second,task.second);
}



//发送文件头， |xqq0502|1228956|myimg.png
void SendFileClass::sendFile(QString senderoc,QString receiveroc,QString filepath)
{
    QFileInfo info(filepath);
    totalsize=info.size();
    currentfilename=info.fileName();
    currentfriendoc=receiveroc;
    sendingfile=new QFile(filepath);
    sendingfile->open(QIODevice::ReadOnly);
    QByteArray resmsg=MyJson::getInstance()->sendFileHead(senderoc,receiveroc,filepath);
    sendfilesocket->write(*Encipher::getInstance()->sha_aesEncrypt(resmsg));
    connect(JSHandler::getInstance(),&JSHandler::s_fileReady,this,&SendFileClass::sendFileBlock,Qt::UniqueConnection);

}


//发送文件块，若发送完毕，则发送完成信号到队列类，执行checkqueue
//若还有任务则触发有任务信号
void SendFileClass::sendFileBlock()
{
    qDebug()<<senddonesize<<" / "<<totalsize;
    int sendSize;
    if(senddonesize<totalsize){
        QString head;
        if(senddonesize+blocksize>totalsize)
            sendSize=totalsize-senddonesize;
        else
            sendSize=blocksize;
        QByteArray filecontent=sendingfile->read(sendSize);
        QByteArray resmsg=MyJson::getInstance()->fileBlock(index,sendSize,filecontent);
        sendfilesocket->write(*Encipher::getInstance()->sha_aesEncrypt(resmsg));
        senddonesize+=sendSize;
        index++;
    }
    else{
        QByteArray resmsg=MyJson::getInstance()->sendFileEnd();
        sendfilesocket->write(*Encipher::getInstance()->sha_aesEncrypt(resmsg));
        sendingfile->close();
        disconnect(JSHandler::getInstance(),&JSHandler::s_fileReady,this,&SendFileClass::sendFileBlock);
        emit s_sendDone();
        QDate date=QDate::currentDate();
        QString pathdate=QString("/%1-%2/").arg(date.year(), 4, 10, QChar('0')).arg(date.month(), 2, 10, QChar('0'));
        ChatBuf::getInstance()->addChat(currentfriendoc,"*"+pathdate+currentfilename,false);
        delete sendingfile;
    }
}


//验证是文件头或是文件块
void SendFileClass::Verify()
{

    QByteArray res=*Encipher::getInstance()->sha_aesDecrypt(sendfilesocket->readAll());

    MyJson::getInstance()->analysisJson(res);
}


